package collector

import (
	"asterisk_calls/conn"
	"github.com/prometheus/client_golang/prometheus"
	"log"
	"regexp"
	"strconv"
	"strings"
	"time"
)

var Conn = conn.AstConn()

var AstActiveCalls = prometheus.NewGauge(prometheus.GaugeOpts{
	Name: "asterisk_active_calls",
	Help: "Current Asterisk Active Calls.",
},
)

var AstActiveChannels = prometheus.NewGauge(prometheus.GaugeOpts{
	Name: "asterisk_active_channels",
	Help: "Current Asterisk Active channels.",
})

func init() {
	Conn.Write([]byte("Action: login\r\nUserName: dishui\r\nSecret: 7moorcom\r\n\n"))
}

func ActiveCalls() float64 {
	Conn.Write([]byte("ACTION: COMMAND\ncommand: core Show Channels\n\n"))
	response := make([]byte, 65536)
	time.Sleep(1 * time.Second)
	_, err := Conn.Read(response)
	if err != nil {
		log.Fatal(err)
	}
	result := string(response)
	r, _ := regexp.Compile(`[0-9]{1,} active calls`)
	res, _ := strconv.ParseFloat(strings.Split(r.FindString(result), " ")[0], 64)
	return res
}

func ActiveChannels() float64 {
	Conn.Write([]byte("ACTION: COMMAND\ncommand: core Show Channels\n\n"))
	response := make([]byte, 65536)
	time.Sleep(1 * time.Second)
	_, err := Conn.Read(response)
	if err != nil {
		log.Fatal(err)
	}
	result := string(response)
	r, _ := regexp.Compile(`[0-9]{1,} active channels`)
	res, _ := strconv.ParseFloat(strings.Split(r.FindString(result), " ")[0], 64)
	return res
}
